import { ListResult } from 'app/modules/base/api-base';
import { Component, OnInit, Injector, Input, ViewEncapsulation } from '@angular/core';
import _ from 'lodash';
import {
  ZoneService,
  BasicConfig,
  AppSetting,
  Software,
  SceneConfig,
} from '../../services/zone.service';
import { DetailBase } from 'app/modules/base/detail-base';
import { ComputerConfigService } from 'app/modules/permission/services/computer-config.service';
import { ConfigMetaBase } from '../../utils/config-meta-base';
import { ConfigMetaService } from '../../services/config-meta.service';
import { FormGroup, Validators } from '@angular/forms';
import { ConfigControlService } from '../../services/config-control.service';
import { SoftwareService } from 'app/modules/software/services/software.service';
import { MatCheckbox } from '@angular/material';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'm-default-permission',
  templateUrl: './default-permission.component.html',
  styleUrls: ['./styles.scss'],
})
export class DefaultPermissionComponent extends DetailBase implements OnInit {
  tab: number = 1;
  editing = false;
  nameSuffixNot = ['py', 'sh'];
  sysConfig: AppSetting[] = [];
  BX_MODE:any=window['HACKER'].BX_MODE;

  canEdit: number;
  sync_period: any;
  checked_period_unitOptions:any;
  checked_period_unitModel:any='d';
  advancedSettingMetas: ConfigMetaBase<number>[]
  scenes;
  currentScene: string;
  sceneConfs: SceneConfig;
  preInstAppAll: Software[];
  notAllowedPorts:"50001,50010";
  // navBtns = ['基础配置', '高级配置', '应用限制', '修复区', '安全配置','认证配置'];
  navBtns = ['基础配置', '高级配置', '应用限制', '修复区', '安全配置'];

  unionForm: FormGroup;

  advancedSettingForm: FormGroup;

  confForm = this.configService.computerConfigForm();
  compVerifyForm: FormGroup = this.fb.group({
    enabled: false,
    netSwitch: [false],//内外网互连控制开关
    intranetNetworkIps: null,//内网IP
    outsideNetworkIps: null,//外网IP
    compVerify: [{}, [Validators.required]],
    repaireGuide: [{}, [Validators.required]],
  });
  repairForm: FormGroup = this.fb.group({
    content: [''],
  });

  checked_period_unitModelChange(){
    // console.log('shit this--:',this,)
    window['HACKER'].updateRouteData({
      'clockModel.checked_period_unit':this.checked_period_unitModel
    },true)
    // try{
    //   window['HACKER'].$bus.routeData.clockModel.checked_period_unit=this.checked_period_unitModel
    // }catch(e){

    // }

    

  }

  preInstForm: FormGroup = this.fb.group({
    preInstalledApp: [{ value: '', disabled: true }],
  });



  restrictedForm: FormGroup = this.fb.group({
    limit_software: [''],
    limit_policy: 0,
  });
  //认证配置tab
  authConfigForm: FormGroup = this.fb.group({
    personalLoginSwitch: false,
  });

  full_zone_fix_html;
  full_zone_verify_script;

  constructor(
    private injector: Injector,
    private zoneService: ZoneService,
    private configService: ComputerConfigService,
    private softwareService: SoftwareService,
    private mcs: ConfigMetaService,
    private ccs: ConfigControlService,
    public http: HttpClient,

  ) {
    super(injector);

  }
  @Input() readonly = false;
  @Input() label = '终端默认配置';
  @Input() userId: number;
  @Input() pcId: number;

  ngOnInit() {
    window['HACKER'].setGlobalVariableForViewModel.call(this)//
    setTimeout(()=>{
      this.BX_MODE=window['HACKER'].BX_MODE;
    })
    if (location.hostname == 'localhost') {
      window['TEST'] = this;
    }
    this.init();
    // this.restrictedForm.controls.limit_policy.valueChanges.subscribe(value => {
    //   this.limit_software_hidden = Boolean(value);
    //   switch (value) {
    //     case 1:
    //       this.rstrHeadText = '白名单'
    //       break;
    //     case 2:
    //       this.rstrHeadText = '黑名单'
    //       break;
    //   }
    // })
    this.http.get('api/admin/config?key=PCLocalEnablePort').subscribe((res: any) => {
      if(res.message){
        this.notAllowedPorts = res.message
      }
    });
    this.compVerifyForm.controls.enabled.valueChanges.subscribe(value => {
      const accessible = !value && !this.compVerifyForm.disabled;
      if (accessible) {
        this.compVerifyForm.controls.compVerify.enable();
        this.compVerifyForm.controls.repaireGuide.enable();
      } else {
        this.compVerifyForm.controls.compVerify.disable();
        this.compVerifyForm.controls.repaireGuide.disable();
      }
    })
  }

  //点击按钮切换组件
  setTab(title: number) {
    this.tab = title;
    this.disableForm()
  }
  //内网接入/远程办公接入tab切换
  async onClickTitle(sceneCode) {
    this.currentScene = sceneCode;
    this.switchScene();
    this.disableForm();
  }

  /**
   * 切换当前场景，用当前的 scene_config 数据重置所有的 form。
   */
  async switchScene() {
    try {
      const conf = this.sceneConfs.message.find((sceneConf) => {
        return sceneConf.scene_code === this.currentScene;
      });
      let pc_config: any = JSON.parse(conf.pc_config);
      pc_config.clock_sync_config = JSON.parse(conf.clock_sync_config)
      this.sync_period = pc_config.clock_sync_config.sync_period;

      this.checked_period_unitModel=pc_config.clock_sync_config.checked_period_unit||'d'
      this.checked_period_unitModelChange()

      
     
      this.checked_period_unitOptions=[{
        label:'天',
        value:'d'
      },{
        label:'小时',
        value:'h'
      },{
        label:'分钟',
        value:'m'
      }]
      pc_config['pam_cracklib']['pwd_policy_switch'] = conf['pwd_policy_switch'];
      this.confForm.patchValue(pc_config);
      this.applyScreenSaverValue()

      // // 高级配置
      this.sysConfig = JSON.parse(conf.sys_setting_config) || [];
      this.advancedSettingMetas = await this.mcs.getMetas(this.sysConfig);
      // 从 metadata 创建表单
      this.advancedSettingForm = this.ccs.toFormGroup(this.advancedSettingMetas);
      /**
       *
       * 查找哪些高级配置有relation值
       * 检测是否修改了该项的值
       * 同步修改对应项
       * */
      let updataKey: any;
      let obj = {};
      this.advancedSettingMetas.forEach(item => {
        // console.log("item:",item)
        if (item.relation) {
          updataKey = item.relation.split(',')
          // 默认启动器为隐藏时禁用相关操作项

          if (!item.value) {
            updataKey.forEach(keyname => {
              this.advancedSettingForm.controls[keyname].disable();
            })
          }
          this.advancedSettingForm.get(item.key).valueChanges.subscribe(data => {
            if (data) {
              updataKey.forEach(keyname => {
                this.advancedSettingForm.controls[keyname].enable();
              })
            } else {
              updataKey.forEach(keyname => {
                this.advancedSettingForm.controls[keyname].disable();
              })
            }
            updataKey.forEach(keyname => {
              //关闭的状态下联动 开启的状态下可独立配置
              if (!data) {
                obj[keyname] = data;
                this.advancedSettingForm.patchValue(obj)
              }
            })
          });
        }
      })

      // 预装应用
      this.preInstAppAll = JSON.parse(conf.sys_software_config);
      const preInstApp = [];
      this.preInstAppAll.forEach((element) => {
        if (element.whether_clip === 0) {
          preInstApp.push(element);
        }
      });
      this.preInstForm.patchValue({ preInstalledApp: preInstApp });

      // 限制应用
      this.restrictedForm.patchValue({
        limit_software: JSON.parse(conf.limit_software),
        limit_policy: conf.limit_policy,
      });

      // 修复区
      if (conf.repair_zone_iptables) {
        this.repairForm.patchValue(JSON.parse(conf.repair_zone_iptables));
      } else {
        this.repairForm.patchValue({ content: [] });
      }
      // 完整性检查 
      this.compVerifyForm.patchValue({
        enabled: Boolean(conf.full_zone_switch),
        repaireGuide: {
          content: conf.full_zone_fix_url,
          name: conf.full_zone_fix_html_name,
          upload_at: new Date()
        },
        compVerify: {
          content: conf.full_zone_verify_script,
          name: conf.full_zone_verify_script_name,
          upload_at: new Date()
        },
        netSwitch: Boolean(conf['network_control_switch']),//内外网互连控制开关
        intranetNetworkIps: conf['intranet_network_ips'],//内网IP
        outsideNetworkIps: conf['outside_network_ips']//外网IP
      });
      //认证配置赋值
      this.authConfigForm.patchValue({
        personalLoginSwitch: conf['personal_login_limit_switch']
      })
      this.full_zone_fix_html = conf.full_zone_fix_html;
      this.full_zone_verify_script = conf.full_zone_verify_script;
    } catch (error) {
      this.toaster.warn('load scene data error', error);
    }
  }

  fetchRepaireGuideContent(file) {
    this.full_zone_fix_html = file.contentText;
    if (!file.file) {
      this.compVerifyForm.patchValue({
        enabled: false,
      });
      this.compVerifyForm.controls.enabled.disable();
    }
    this.compVerifyForm.markAsDirty();
  }

  fetchCompVerifyContent(file) {
    this.compVerifyForm.controls.enabled.enable();
    if (!file.file) {
      this.compVerifyForm.patchValue({
        enabled: false,
      });
      this.compVerifyForm.controls.enabled.disable();
    }
    this.full_zone_verify_script = file.contentText;
    this.compVerifyForm.markAsDirty();
  }

  //初始化数据
  async init() {
    const zid: number = Number(this.route.snapshot.queryParamMap.get('id'));
    // return false;
    const resp = await this.zoneService.getAreaScene(zid);
    // alert(2)
    this.scenes = resp.message;
    // console.log('resp.message---:',resp.message)
    this.currentScene = this.currentScene ? this.currentScene : this.scenes[0].scene_code;
    if (!this.readonly) {
      // alert(11)
      this.sceneConfs = await this.zoneService.getSceneConfig(zid);


      this.canEdit = this.sceneConfs.message[0].can_edit
      await this.switchScene();

    } else {
      // alert(22)
      this.zoneService
        .getConfig(zid, this.pcId, this.userId)
        .then((value) => {
          this.confForm.patchValue(value)
        });
    }

    this.disableForm();
  }

  disableForm() {
    this.editing = false;
    this.confForm.disable();
    this.advancedSettingForm.disable();
    this.repairForm.disable();
    this.compVerifyForm.disable();
    this.compVerifyForm.controls.compVerify.disable();
    this.compVerifyForm.controls.repaireGuide.disable();
    this.restrictedForm.disable();
    this.authConfigForm.disable()
  }

  enableForm() {
    this.editing = true;
    this.confForm.enable();

    console.log('this.confForm--:', this.confForm.value)

    //设置屏保路径显示值


    // try {
    //   if ('screensaver_file_path' in this.sceneConfs) {
    //     this.sceneConfs.screensaver.screensaver_file_path = this.sceneConfs.screensaver_file_path
    //   }
    // } catch (e) {
    //   console.warn(e)
    // }


    this.advancedSettingForm.enable();
    this.repairForm.enable();
    this.restrictedForm.enable();
    this.compVerifyForm.enable();
    this.compVerifyForm.controls.compVerify.enable();
    this.compVerifyForm.controls.repaireGuide.enable();
    this.authConfigForm.enable()
    if (!this.compVerifyForm.controls.compVerify.value.name) {
      this.compVerifyForm.controls.enabled.disable();
    }
    // 完整性检查开关开启时，不允许进行增删改查操作
    if (this.compVerifyForm.controls.enabled.value) {
      this.compVerifyForm.controls.compVerify.disable()
      this.compVerifyForm.controls.repaireGuide.disable()
    }
    if (!this.advancedSettingForm.controls.launcher.value) {
      let updataKey: any;
      let obj = {};
      this.advancedSettingMetas.forEach(item => {
        if (item.relation) {
          updataKey = item.relation.split(',')
          // 默认启动器为隐藏时禁用相关操作项
          if (!item.value) {
            updataKey.forEach(keyname => {
              this.advancedSettingForm.controls[keyname].disable();
            })
          }
        }
      })
    }

    //特殊处理  如果设置时钟同步则 不可勾选日期时间
    if(this.confForm.value.clock_sync_config.sync_switch){
      this.advancedSettingForm.controls['datetime'].disable();
    }

    this.applyScreenSaverValue()




  }

  applyScreenSaverValue() {
    // setTimeout(() => {
    let confFormValue = this.confForm.value;
    const conf: any = this.sceneConfs.message.find((sceneConf) => {
      return sceneConf.scene_code === this.currentScene;
    });

    // alert(confFormValue.screensaver)
    if ('screensaver' in conf) {
      confFormValue.screensaver_file_path.name = conf.screensaver.split('/').reverse()[0]
      //  || '暂无配置'
      confFormValue.screensaver_file_path.content = conf.screensaver
      //  || '暂无配置'

      // console.log("confFormValue--:", confFormValue)
      this.confForm.patchValue(confFormValue);
    }
    // })
  }

  async submit2() {
    console.log('advancedSettingForm.value', this.advancedSettingForm.value);
    console.log('combineSubmitedMetas', JSON.stringify(this.combineSubmitedMetas()));
  }

  async submit() {
   
    // if (this.confForm.invalid || this.advancedSettingForm.invalid) {
    //   return;
    // }
    //--------
    // 基础配置
    const pcConfig: BasicConfig = _.cloneDeep(this.confForm.value);
    // console.log('this.confForm.value and clonedNodes:', this.confForm.value, pcConfig)
    const formData = new FormData();


    let scriptUrl: string = _.get(pcConfig, 'script.content', '');
    let screensaver_file_path_value: string = _.get(pcConfig, 'screensaver_file_path.content', '');
    // TODO irregular practices
    pcConfig.script['upload_at'] = new Date();
    if (scriptUrl.startsWith('blob:')) {
      const scriptBlob = await fetch(scriptUrl).then((resp) => resp.blob());
      formData.append('script', scriptBlob, pcConfig.script.name);
    }
    if (screensaver_file_path_value.startsWith('blob:')) {
      const screensaver_file_pathBlob = await fetch(screensaver_file_path_value).then((resp) => resp.blob());
      formData.append('screensaver', screensaver_file_pathBlob, pcConfig.screensaver_file_path.name);
      // formData.append('screensaver_file_path', screensaver_file_pathBlob, pcConfig.screensaver_file_path.name);
    }
    // else {
    // screensaver_file_path
    // pcConfig.screensaver.screensaver_file_path = screensaver_file_path_value
    // }
    const wallpaperUrl: string = _.get(pcConfig, 'wallpaper.image', '');
    if (wallpaperUrl.startsWith('blob:')) {
      pcConfig.wallpaper.image = '';
      const wallpaperBlob = await fetch(wallpaperUrl).then((resp) => resp.blob());
      formData.append('wallpaper', wallpaperBlob);
    }
    //基础配置
    if (this.confForm.dirty) {

      if(pcConfig.clock_sync_config.ntp_server.trim()==''){
        pcConfig.clock_sync_config.ntp_server=location.hostname
      }

      formData.append('pc_config', JSON.stringify(pcConfig));
      formData.append('pwd_policy_switch', String(Number(pcConfig['pam_cracklib']['pwd_policy_switch'])));//后台接口返回的pwd_policy_switch没有在pc_config层下，结构变化穿插
    }
    // 时钟同步
    if (this.confForm.dirty) {
      pcConfig.clock_sync_config.sync_switch = +pcConfig.clock_sync_config.sync_switch;
      if(pcConfig.clock_sync_config.ntp_server.trim()==''){
        pcConfig.clock_sync_config.ntp_server=location.hostname
      }
      formData.append('clock_sync_config', JSON.stringify(pcConfig.clock_sync_config));
    }
    // 预装软件
    if (this.preInstForm.dirty) {
      const selectedAppIds = this.preInstForm.controls.preInstalledApp.value.map((item) => {
        return item.app_id;
      });
      const preInstApps = this.preInstAppAll.map((app) => {
        if (selectedAppIds.includes(app.app_id)) {
          app.whether_clip = 0;
        } else {
          app.whether_clip = 1;
        }
        return app;
      });
      formData.append('sys_software_config', JSON.stringify(preInstApps));
    }

    // 高级配置
    if (this.advancedSettingForm.dirty) {
      formData.append('sys_setting_config', JSON.stringify(this.combineSubmitedMetas()));
    }

    // 防火墙配置
    if (this.repairForm.dirty) {
      formData.append('repair_zone_iptables', JSON.stringify(this.repairForm.value));
    }

    // 限制应用
    if (this.restrictedForm.dirty) {
      formData.append(
        'limit_software',
        JSON.stringify(this.restrictedForm.controls.limit_software.value),
      );
      formData.append('limit_policy', this.restrictedForm.controls.limit_policy.value);
    }
    // 完整性检查
    const full_zone_fix_html_name = this.compVerifyForm.controls.repaireGuide.value.name;
    const full_zone_verify_script_name = this.compVerifyForm.controls.compVerify.value.name;
    if (this.compVerifyForm.dirty) {
      formData.append('full_zone_switch', String(Number(this.compVerifyForm.get('enabled').value)));
      formData.append(
        'full_zone_verify_script',
        full_zone_verify_script_name ? this.full_zone_verify_script : '',
      );
      formData.append('full_zone_fix_html', full_zone_fix_html_name ? this.full_zone_fix_html : '');
      formData.append('full_zone_fix_html_name', full_zone_fix_html_name);
      formData.append('full_zone_verify_script_name', full_zone_verify_script_name);
      formData.append('network_control_switch', String(Number(this.compVerifyForm.get('netSwitch').value)));//内外网互联控制开关
      formData.append('intranet_network_ips', String(this.compVerifyForm.get('intranetNetworkIps').value));//内网ip
      formData.append('outside_network_ips', String(this.compVerifyForm.get('outsideNetworkIps').value));//外网ip
    }
    //认证配置
    if (this.authConfigForm.dirty) {
      formData.append('personal_login_limit_switch', String(Number(this.authConfigForm.get('personalLoginSwitch').value)));
    }

    formData.append('code', this.currentScene);
    const zid = this.route.snapshot.queryParamMap.get('id');

    const intranetNetworkIps = this.compVerifyForm.get('intranetNetworkIps').value;//内网IP
    const outsideNetworkIps = this.compVerifyForm.get('outsideNetworkIps').value;//外网ip
    const netSwitch = this.compVerifyForm.get('netSwitch').value;//内外网互联开关
    //判断内网和外网ip输入时是否为空，有空值则不能提交
    if (intranetNetworkIps && outsideNetworkIps || this.tab != 5 || !netSwitch) {
      await this.zoneService.setConfig(Number(zid), formData);
      // let formValue =JSON.parse(JSON.stringify(this.combineSubmitedMetas()))
      this.init();
      this.disableForm();
    } else {
      this.toaster.warn('内网IP和外网IP不能为空');
    }
    // console.log(formValue)
    // this.advancedSettingForm.patchValue(formValue)
  }

  combineSubmitedMetas() {
    let sysSubmitedConfig = [];
    if (this.sysConfig) {
      sysSubmitedConfig = this.sysConfig.map((config) => {
        // convert boolean to numric
        config.whether_enable = + this.advancedSettingForm.controls[config.en_name.trim()].value
        return config;
      });
    }
    return sysSubmitedConfig;
  }

  routeToRepairGuidePage(file) {
    window.open(`/api${file.content}`, '_blank');
  }

  markAsDirty() {
    this.compVerifyForm.markAsDirty();

    localStorage.setItem('modelId', '1')
    localStorage.setItem('modelTexturesId', '2')
  }
}
